using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NorthwindWeb.Models;

namespace NorthwindWeb.Controllers
{   
    public class ShipperController : Controller
    {
		private readonly IShipperRepository shipperRepository;

		// If you are using Dependency Injection, you can delete the following constructor
        public ShipperController() : this(new ShipperRepository())
        {
        }

        public ShipperController(IShipperRepository shipperRepository)
        {
			this.shipperRepository = shipperRepository;
        }

        //
        // GET: /Shipper/

        public ViewResult Index()
        {
            return View(shipperRepository.AllIncluding(shipper => shipper.Orders));
        }

        //
        // POST: /Shipper/Create

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "ShipperID")]Shipper shipper)
        {
            if (ModelState.IsValid) {
                shipperRepository.InsertOrUpdate(shipper);
                shipperRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }
        //
        // POST: /Shipper/Edit/5

        [HttpPost]
        public ActionResult Edit(Shipper shipper)
        {
            if (ModelState.IsValid) {
                shipperRepository.InsertOrUpdate(shipper);
                shipperRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Shipper/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            shipperRepository.Delete(id);
            shipperRepository.Save();

            return RedirectToAction("Index");
        }

        
        public JsonResult shipperGridData(int rows, int page)
        {
        	var count = shipperRepository.All.Count();
            var pageData = shipperRepository.All.OrderBy(x => x.ShipperID).Skip((page - 1) * rows).Take(rows).Select(o => new {ShipperID = o.ShipperID, CompanyName = o.CompanyName, Phone = o.Phone});
            return Json(new { 
            page = page,
            records = count,
            rows = pageData,
            total = Math.Ceiling((decimal)count / rows)
            }, JsonRequestBehavior.AllowGet);
        }
        
        
    }
}

